package pers.cz.chat.filter;

import pers.cz.chat.constants.Commands;
import pers.cz.chat.constants.JefClolorEnum;
import pers.cz.chat.utils.BaseUtils;
import pers.cz.chat.utils.LogUtils;
import pers.cz.netty.filter.FilterHandler;
import pers.cz.netty.filter.FilterHandlerContext;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.util.ContextHolder;

/**
 * @version 1.0
 * @description: 切换聊天好友拦截器
 * @author: ChengZhi 0336
 * @create: 2025-01-10 08:42
 **/
public class SwitchUserFilter implements FilterHandler<Message, Object> {
	@Override
	public boolean approve(Message message, Object obj, FilterHandlerContext<Message, Object> handlerContext) {

		Object contentOriginal = message.getContent();
		if (contentOriginal instanceof String) {
			String content = (String) contentOriginal;
			// 拦截未指定聊天的对象的消息
			String targetUserName = ContextHolder.getRequestContext().get("targetUserName");
			if (targetUserName == null || targetUserName.isEmpty()) {

				LogUtils.print(JefClolorEnum.WHITE, "请指定聊天对象！");
				if (!BaseUtils.isCommand(content)) {
					return true;
				}
			}

			if (content.trim().startsWith(Commands.CONN.getCommand())) {
				// 为什么+1？因为-conn test, conn后面有个空格
				String targetUser = content.substring(Commands.CONN.getCommand().length()+1);
				LogUtils.print(JefClolorEnum.WHITE, "当前聊天对象已经切换为：" + targetUser);
				ContextHolder.getRequestContext().put("targetUserName", targetUser);
				return true;
			}
		}

		return handlerContext.doFilter(message, obj);
	}
}
